import React, { useEffect, useState } from 'react'
import UserList from '@/views/sandBox/user-manage/UserList'
import RoleList from '@/views/sandBox/right-manage/RoleList'
import Home from '@/views/sandBox/Home/Home'
import RightList from '@/views/sandBox/right-manage/RightList'
import Nopermission from '@/views/sandBox/Nopermission/Nopermission'
import { Routes, Route, Navigate } from 'react-router-dom'
import NewsAdd from '@/views/sandBox/new-manage/NewsAdd'
import NewsDraft from '@/views/sandBox/new-manage/NewsDraft'
import NewsCategory from '@/views/sandBox/new-manage/NewsCategory'
import Aduit from '@/views/sandBox/audit-manage/Aduit'
import AduitList from '@/views/sandBox/audit-manage/AduitList'
import Unpublished from '@/views/sandBox/publish-manage/Unpublished'
import Published from '@/views/sandBox/publish-manage/Published'
import Sunset from '@/views/sandBox/publish-manage/Sunset'
import axios from 'axios'

const loaclRouterList: { [key: string]: any } = {
  '/home': <Home></Home>,
  '/user-manage/list': <UserList></UserList>,
  '/right-manage/role/list': <RoleList></RoleList>,
  '/right-manage/right/list': <RightList></RightList>,
  // '*': Nopermission,
  '/news-manage/add': <NewsAdd></NewsAdd>,
  '/news-manage/draft': <NewsDraft></NewsDraft>,
  '/news-manage/category': <NewsCategory></NewsCategory>,
  '/aduit-manage/aduit': <Aduit></Aduit>,
  '/aduit-manage/list': <AduitList></AduitList>,
  '/publish-manage/unpublished': <Unpublished></Unpublished>,
  '/publish-manage/published': <Published></Published>,
  '/publish-manage/sunset': <Sunset></Sunset>
}
export default function NewsRouter() {
  const {
    role: { rights }
  } = JSON.parse(localStorage.getItem('token') || '{}')
  const address = ``
  const [backRouteList, setBackRouteList] = useState<any[]>([])
  useEffect(() => {
    Promise.all([axios.get(`${address}/rights`), axios.get(`${address}/children`)]).then((res) => {
      console.log(res)

      setBackRouteList([...res[0].data, ...res[1].data])
      console.log(backRouteList)
    })
  }, [])
  const checkRoute = (item: any) => {
    return loaclRouterList[item.key] && item.pagepermisson === 1
  }
  const checkuserPermission = (item: any) => {
    return rights.includes(item.key)
  }
  return (
    <Routes>
      {/* 检查当前用户用户是否有路由权限和登录权限 */}
      {backRouteList.map((item: any) => {
        if (checkRoute(item) && checkuserPermission(item)) {
          return <Route path={item.key} key={item.key} element={loaclRouterList[item.key]}></Route>
        }
        return null
      })}
      {/* 重定向 */}
      <Route path="/" element={<Navigate to="/home" />} />
      {backRouteList.length > 0 && <Route path="*" element={<Nopermission></Nopermission>} />}
    </Routes>
  )
}
